"use strict";

/**
 * @param {TemplateStringsArray} s
 * @returns {string}
 */
const red = (s) => `\u001B[41m${s}\u001B[0m`;
/**
 * @param {TemplateStringsArray} s
 * @returns {string}
 */
const green = (s) => `\u001B[42m${s}\u001B[0m`;
const bar = green`---------------------`;
class DonePlugin {
  static name = "DonePlugin";

  constructor() {
    console.time(red`webpack-done`);
    console.time(red`webpack-final`);
  }

  /**
   * @type {number}
   */
  onceDone = 0;

  /**
   * @type {number}
   */
  onceFin = 0;

  /**
   * @param {import('webpack').Compiler} compiler
   * @returns {void}
   */
  apply(compiler) {
    compiler.hooks.done.tap(DonePlugin.name, (_) => {
      if (!this.onceDone) {
        console.timeEnd(red`webpack-done`);
        this.onceDone += 1;
      }
      console.info("::>End", bar, new Date().toLocaleString(), bar);
    });
    compiler.hooks.afterDone.tap(DonePlugin.name, (_) => {
      if (!this.onceFin) {
        console.timeEnd(red`webpack-final`);
        this.onceFin += 1;
      }
      console.info("::>Fin", bar, new Date().toLocaleString(), bar);
      process.env.NODE_ENV !== "production" &&
        console.log(
          `Open: \u001B[32m http://localhost:${process.env.PORT}/ \u001B[0m`,
        );
    });
  }

  toJSON() {
    return {
      name: DonePlugin.name,
      onceDone: this.onceDone,
      onceFin: this.onceFin,
    };
  }
}

module.exports = DonePlugin;
